package com.xugongzhang.demo;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author X
 * @date 2022/6/28 1:04
 */
public class CompletableFutureUseDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "进来了...");
            int i = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("计算了一秒钟");
            if (i > 5) {
                int j = 10 / 0;
            }
            return i;
        }, executorService).whenComplete((v, e) -> {
           if (e == null) {
               System.out.println("计算完成 -->" + v);
           }
        }).exceptionally(e -> {
            e.printStackTrace();
            System.out.println("发生了异常-->" + e.getCause() + "***" + e.getMessage());
            return null;
        });

        executorService.shutdown();
        System.out.println(Thread.currentThread().getName() + "主线程忙其他任务去了");
        // 主线程不能立即结束,否则completableFuture默认使用的线程会立刻关闭,有点像守护线程,所以主线程暂停一下
        // TimeUnit.SECONDS.sleep(2);
    }
}
